package com.example.wechat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.wechat.database.WeChatDatabaseManager;
import com.example.wechat.model.Friend;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private WeChatDatabaseManager dbManager;
    private LinearLayout navWechat, navContacts, navDiscover, navMe;
    private TextView titleText;
    private ListView chatList;
    private ImageButton btnAdd, btnSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化数据库
        dbManager = new WeChatDatabaseManager(this);
        dbManager.open();

        // 初始化视图
        initViews();
        // 设置点击事件
        setClickListeners();
        // 默认显示微信页面
        showWeChatPage();
    }

    private void initViews() {
        navWechat = findViewById(R.id.nav_wechat);
        navContacts = findViewById(R.id.nav_contacts);
        navDiscover = findViewById(R.id.nav_discover);
        navMe = findViewById(R.id.nav_me);
        titleText = findViewById(R.id.title_text);
        chatList = findViewById(R.id.chat_list);
        btnAdd = findViewById(R.id.btn_add);
        btnSearch = findViewById(R.id.btn_search);

        // 设置列表项点击事件
        chatList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                handleListItemClick(position);
            }
        });
    }

    private void handleListItemClick(int position) {
        String currentTitle = titleText.getText().toString();
        if (currentTitle.equals("微信")) {
            // 获取点击的好友名称
            String friendName = (String) chatList.getAdapter().getItem(position);
            // 创建Intent启动聊天界面
            Intent intent = new Intent(MainActivity.this, ChatActivity.class);
            intent.putExtra("friend_name", friendName);
            intent.putExtra("friend_id", position + 1); // 使用position + 1作为好友ID
            startActivity(intent);
        } else if (currentTitle.equals("发现")) {
            Toast.makeText(this, "发现功能开发中", Toast.LENGTH_SHORT).show();
        } else if (currentTitle.equals("我")) {
            Toast.makeText(this, "个人中心功能开发中", Toast.LENGTH_SHORT).show();
        }
    }

    private void setClickListeners() {
        navWechat.setOnClickListener(this);
        navContacts.setOnClickListener(this);
        navDiscover.setOnClickListener(this);
        navMe.setOnClickListener(this);
        btnAdd.setOnClickListener(this);
        btnSearch.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        // 重置所有导航项的文字颜色
        resetNavigation();

        if (v.getId() == R.id.nav_wechat) {
            showWeChatPage();
            setNavSelected(navWechat);
        } else if (v.getId() == R.id.nav_contacts) {
            showContactsPage();
            setNavSelected(navContacts);
        } else if (v.getId() == R.id.nav_discover) {
            showDiscoverPage();
            setNavSelected(navDiscover);
        } else if (v.getId() == R.id.nav_me) {
            showMePage();
            setNavSelected(navMe);
        } else if (v.getId() == R.id.btn_add) {
            showAddMenu();
        } else if (v.getId() == R.id.btn_search) {
            showSearch();
        }
    }

    private void resetNavigation() {
        ((TextView) navWechat.findViewById(android.R.id.text1)).setTextColor(0xFF666666);
        ((TextView) navContacts.findViewById(android.R.id.text1)).setTextColor(0xFF666666);
        ((TextView) navDiscover.findViewById(android.R.id.text1)).setTextColor(0xFF666666);
        ((TextView) navMe.findViewById(android.R.id.text1)).setTextColor(0xFF666666);
    }

    private void setNavSelected(LinearLayout nav) {
        ((TextView) nav.findViewById(android.R.id.text1)).setTextColor(0xFF45C01A);
    }

    private void showWeChatPage() {
        titleText.setText("微信");
        // 显示聊天列表
        List<String> chatItems = Arrays.asList(
            "张三",
            "李四",
            "微信团队",
            "群聊",
            "家庭群"
        );
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_list_item_1, chatItems);
        chatList.setAdapter(adapter);
    }

    private void showContactsPage() {
        titleText.setText("通讯录");
        // 从数据库获取好友列表
        List<String> contacts = new ArrayList<>();
        contacts.add("新的朋友");
        contacts.add("群聊");
        contacts.add("标签");
        contacts.add("公众号");
        
        // 从数据库获取好友列表
        List<Friend> friends = dbManager.getAllFriends();
        for (Friend friend : friends) {
            // 优先显示备注名，如果没有备注名则显示昵称
            String displayName = friend.getRemark().isEmpty() ? friend.getNickname() : friend.getRemark();
            contacts.add(displayName);
        }
        
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_list_item_1, contacts);
        chatList.setAdapter(adapter);
    }

    private void showDiscoverPage() {
        titleText.setText("发现");
        // 显示发现页面的选项
        List<String> discoverItems = Arrays.asList(
            "朋友圈",
            "视频号",
            "扫一扫",
            "摇一摇",
            "看一看",
            "搜一搜",
            "直播",
            "附近"
        );
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_list_item_1, discoverItems);
        chatList.setAdapter(adapter);
        // 添加点击事件，点击朋友圈跳转
        chatList.setOnItemClickListener((parent, view, position, id) -> {
            if (position == 0) {
                startActivity(new Intent(MainActivity.this, MomentsActivity.class));
            }
        });
    }

    private void showMePage() {
        titleText.setText("我");
        // 显示个人页面的选项
        List<String> meItems = Arrays.asList(
            "个人资料",
            "支付",
            "收藏",
            "相册",
            "卡包",
            "表情",
            "设置"
        );
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_list_item_1, meItems);
        chatList.setAdapter(adapter);
        // 添加点击事件，点击"个人资料"跳转
        chatList.setOnItemClickListener((parent, view, position, id) -> {
            if (position == 0) {
                startActivity(new Intent(MainActivity.this, ProfileActivity.class));
            } else if (position == 1) {
                startActivity(new Intent(MainActivity.this, PayActivity.class));
            }
        });
    }

    private void showAddMenu() {
        PopupMenu popup = new PopupMenu(this, btnAdd);
        popup.getMenuInflater().inflate(R.menu.menu_add, popup.getMenu());
        
        popup.setOnMenuItemClickListener(item -> {
            int itemId = item.getItemId();
            if (itemId == R.id.action_add_friend) {
                startActivity(new Intent(MainActivity.this, FriendManagementActivity.class));
                return true;
            }
            return false;
        });
        
        popup.show();
    }

    private void showSearch() {
        Toast.makeText(this, "显示搜索界面", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbManager != null) {
            dbManager.close();
        }
        // 清理输入法相关资源
        if (getCurrentFocus() != null) {
            getCurrentFocus().clearFocus();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 隐藏输入法
        if (getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
    }
}